package com.ruoyi.framework.strategy;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.WxApiLoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.WxApiTokenService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WxApiAuthenticationStrategy implements AuthenticationStrategy {

    @Autowired
    private WxApiTokenService apiTokenService;

    public WxApiAuthenticationStrategy(WxApiTokenService apiTokenService) {
        this.apiTokenService = apiTokenService;
    }

    @Override
    public void authenticate(HttpServletRequest request) throws ServletException, IOException {
        WxApiLoginUser wxApiLoginUser = apiTokenService.getLoginUser(request);
        if (StringUtils.isNotNull(wxApiLoginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
            apiTokenService.verifyToken(wxApiLoginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                    wxApiLoginUser, null, wxApiLoginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
    }
}
